#include "FieldValidator.h"

#include <qapplication.h>

#include <QLineEdit>
#include <QValidator>

FieldValidator::FieldValidator(QWidget *parent) :
    QWidget(parent)
{
    button = nullptr;
    formValid = false;

	redPalette = QApplication::palette();
	redPalette.setColor(QPalette::Base, QColor::fromRgb(255, 221, 221));

	whitePalette = QApplication::palette();
	whitePalette.setColor(QPalette::Base, QColor::fromRgb(255, 255, 255));
}

void FieldValidator::addAllFields()
{
    // Get list of all line edit fields
    QList<QLineEdit *> lineEditList = parent()->findChildren<QLineEdit *>();

    // Connect each field's change signal to the check_fields slot so that the
    // form is checked every time a field is edited
    for (int i = 0; i < lineEditList.size(); i++)
    {
        connect(lineEditList.at(i), SIGNAL(textChanged(QString)), this, SLOT(check_fields(QString)));
        widgetList.push_back(lineEditList.at(i));
    }
}

void FieldValidator::setButton(QPushButton *button)
{
    this->button = button;
}

void FieldValidator::resetFields()
{
    for(int i = 0; i < widgetList.size(); i++)
    {
        QLineEdit * field = widgetList.at(i);

        field->clear();
        field->setStyleSheet("");
    }
}

void FieldValidator::check_fields(QString)
{
    bool isValid = true;

    for(int i = 0; i < widgetList.size(); i++)
    {
        QLineEdit * field = widgetList.at(i);

        const QValidator * validator = field->validator();
        int pos = 0;

        if (field->text().isEmpty() ||
            (validator != 0 &&
             validator->validate(field->text(), pos)
                     == QValidator::Intermediate))
        {
            isValid = false;
            //field->setStyleSheet("QLineEdit{background: #ffdddd}");
			field->setPalette(redPalette);
        }
        else
		{
            //field->setStyleSheet("");
			field->setPalette(whitePalette);
		}
    }

    if (button != nullptr)
    {
        if (isValid != formValid)
        {
            button->setEnabled(isValid);
            formValid = isValid;
        }
    }
}
